<template>
  <el-dialog
    width="600"
    v-model="state.visible"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
  >
    <template v-if="state.actionType == 'detail'">
      <el-descriptions title="点位类型信息" :column="2">
        <el-descriptions-item label="点位类型名称:">
          {{ itemDetail?.typeName }}
        </el-descriptions-item>
        <el-descriptions-item label="城市标签:">
          {{ cityNameOptions.find((i) => i === state.formModel.cityName) }}
        </el-descriptions-item>
        <el-descriptions-item label="状态:">
          <dict-tag
            style="display: inline-block"
            :options="sys_common_staus"
            :value="itemDetail?.enable"
          />
        </el-descriptions-item>
        <el-descriptions-item label="点位标签:">
          {{ itemDetail?.label === 1 ? '特殊点位' : '普通点位' }}
        </el-descriptions-item>
        <el-descriptions-item label="点位开售时间:">
          {{ itemDetail?.saleBeginTime }}
        </el-descriptions-item>
        <el-descriptions-item label="点位停售时间:">
          {{ itemDetail?.saleEndTime }}
        </el-descriptions-item>
        <el-descriptions-item label="操作人:">
          {{ itemDetail?.updateName }}
        </el-descriptions-item>
        <el-descriptions-item label="操作时间:">
          {{ itemDetail?.updateTime }}
        </el-descriptions-item>
      </el-descriptions>
    </template>

    <template v-else>
      <el-form
        ref="dialogFormRef"
        :model="state.formModel"
        label-position="right"
        :rules="state.formRules"
        label-width="auto"
      >
        <el-form-item label="城市标签" prop="cityName">
          <el-select
            :disabled="editDisabled"
            v-model="state.formModel.cityName"
            placeholder="请选择"
          >
            <el-option v-for="item in cityNameOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="点位类型名称" prop="typeName">
          <el-input
            style="width: 215px"
            maxLength="50"
            v-model.trim="state.formModel.typeName"
            placeholder="点位类型名称"
          />
        </el-form-item>
        <el-form-item label="点位标签" prop="type">
          <el-select :disabled="editDisabled" v-model="state.formModel.type" placeholder="请选择">
            <el-option label="特殊点位" :value="1" />
            <el-option label="普通点位" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="点位开售时间" prop="saleBeginTime">
          <el-time-picker
            format="HH:mm"
            v-model="state.formModel.saleBeginTime"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="点位停售时间" prop="saleEndTime">
          <el-time-picker
            format="HH:mm"
            v-model="state.formModel.saleEndTime"
            placeholder="请选择"
          />
        </el-form-item>
      </el-form>
    </template>

    <template #footer>
      <template v-if="state.actionType == 'detail'">
        <el-button @click="handleAction(false)">关闭</el-button>
      </template>

      <template v-else>
        <el-button @click="handleAction(false)">取消</el-button>

        <el-button :loading="state.loading" type="primary" @click="handleAction(true)">
          {{ state.actionType == 'add' ? '新增' : '更新' }}
        </el-button>
      </template>
    </template>
  </el-dialog>
</template>

<script setup>
import { formRules } from '@/utils/valid/formRules'
import { parseTime, handleUpdConfirm } from '@/utils/tools'
import { updatePointType, addPointType } from '@/api/organization/pointType'
import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)
const { proxy } = getCurrentInstance()
const emit = defineEmits(['refresh'])
const editDisabled = computed(() => state.actionType === 'edit')
const { sys_common_staus } = proxy.useDict('sys_common_staus')
const dialogFormRef = ref()
const itemDetail = ref({})
const state = reactive({
  loading: false,
  visible: false,
  formModel: {
    typeName: '',
    saleBeginTime: '',
    cityName: '',
    type: ''
  },
  formRules: {
    typeName: formRules.set('请输入点位类型名称'),
    saleBeginTime: formRules.set('请选择开售时间', 'change'),
    saleEndTime: [
      formRules.set('请选择停售时间', 'change'),
      { trigger: 'change', validator: validateTime }
    ],
    cityName: formRules.set('请选择城市', 'change'),
    type: formRules.set('请选择点位标签', 'change')
  },
  actionType: 'add',
  itemDetail: {}
})

// 时间范围校验
function validateTime(rule, value, cb) {
  const { saleBeginTime, saleEndTime } = state.formModel
  if (saleBeginTime && saleEndTime && saleBeginTime >= saleEndTime) {
    return cb(new Error('开售停售时间冲突'))
  }
  cb()
}

/**
 * 弹窗操作
 * @param {boolean} confirm
 */
function handleAction(confirm) {
  if (confirm) {
    dialogFormRef.value?.validate((valid) => {
      if (valid) {
        const isAdd = state.actionType == 'add'
        handleUpdConfirm(isAdd, '确认要修改当前点位类型？').then(async () => {
          state.loading = true
          let { saleBeginTime, saleEndTime, positionTypeId, typeName, cityName, type } =
            state.formModel
          saleBeginTime = parseTime(new Date(saleBeginTime), '{h}:{i}')
          saleEndTime = parseTime(new Date(saleEndTime), '{h}:{i}')

          const fetchMethod = isAdd ? addPointType : updatePointType
          fetchMethod({ positionTypeId, typeName, saleBeginTime, saleEndTime, cityName, type })
            .then(() => {
              proxy.$modal.msgSuccess(isAdd ? '新增成功' : '更新成功')
              emit('refresh')
              onHide()
            })
            .finally(() => {
              state.loading = false
            })
        })
      }
    })
  } else {
    onHide()
  }
}

function onHide() {
  itemDetail.value = {}
  state.visible = false
  state.loading = false
  dialogFormRef.value.resetFields()
}

function init(obj = {}, cityName = '') {
  if (obj.actionType) {
    const { actionType, ...data } = obj
    state.actionType = actionType

    if (actionType == 'detail') {
      itemDetail.value = data
    } else {
      state.formModel = data
      state.formModel.cityName = cityName
    }

    state.visible = true
  }
}

defineExpose({ init })
</script>
